from tensorflow import keras
import matplotlib.pyplot as plt

# 加载数据集
(train_image, train_label), (test_image, test_label) = keras.datasets.fashion_mnist.load_data()

# 打印一张图片
plt.imshow(train_image[0])
plt.show()

train_image = train_image / 255
test_image = test_image / 255

input1 = keras.Input(shape=(28, 28))
x = keras.layers.Flatten()(input1)
x = keras.layers.Dense(32, activation='relu')(x)
x = keras.layers.Dropout(0.5)(x)
x = keras.layers.Dense(64, activation='relu')(x)
output = keras.layers.Dense(10, activation='softmax')(x)
model = keras.Model(inputs=input1, outputs=output)

model.summary()

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['acc'])

history = model.fit(train_image, train_label, epochs=20)

plt.plot(history.epoch, history.history.get('acc'))
plt.xlabel('epochs')
plt.ylabel('acc')
plt.show()

# 用测试集对训练好的模型进行测试
print(model.evaluate(test_image, test_label))

